package e2e;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLParser {

    public static List<String> parseXMLDirectory(File directory) {
        List<String> transactionIds = new ArrayList<>();
        parseXMLFiles(directory, transactionIds);
        return transactionIds;
    }

    private static void parseXMLFiles(File directory, List<String> transactionIds) {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        parseXMLFiles(file, transactionIds);
                    } else if (file.isFile() && file.getName().endsWith(".xml")) {
                        transactionIds.addAll(parseXMLFile(file));
                    }
                }
            }
        }
    }

    private static List<String> parseXMLFile(File file) {
        List<String> transactionIds = new ArrayList<>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(file);
            Element root = document.getDocumentElement();
            NodeList serviceNodes = root.getElementsByTagName("service");
            for (int i = 0; i < serviceNodes.getLength(); i++) {
                Node serviceNode = serviceNodes.item(i);
                if (serviceNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element serviceElement = (Element) serviceNode;
                    String transactionId = serviceElement.getAttribute("transaction-id");
                    transactionIds.add(transactionId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return transactionIds;
    }
}
